<?php

namespace App\Http\Middleware;

use App\Jobs\LogJob;
use Closure;
use Illuminate\Support\Facades\Auth;

class RequestLogMiddleware
{
    protected function uuid($guard = null)
    {
        return ($user = $guard ? Auth::guard($guard)->user() : Auth::user()) ? $user->uuid : null;
    }
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $time1 = microtime(true);
        $response = $next($request);
        $time2 = microtime(true);

        //通过中间件 记录操作记录
        LogJob::dispatch([
            'url'       => $request->path(),
            'ip'   => $request->ip(),
            'header'   => json_encode($request->header() ,JSON_UNESCAPED_UNICODE),
            'request'   => json_encode($request->all() ,JSON_UNESCAPED_UNICODE),
            'member_uuid'   => $this->uuid('member'),
            'response'  => json_encode($response ,JSON_UNESCAPED_UNICODE),
            'time'      => sprintf("%.4f",($time2-$time1)),
        ])->onQueue('log');

        return $response;
    }
}
